package org.hao.samples.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hao.samples.model.PagerModel;
import org.hao.samples.model.Student;
import org.hao.samples.model.StudentVO;
import org.hao.samples.service.StudentService;
import org.hao.samples.util.ExcelUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class StudentController {
	@Autowired
	private StudentService studentService;

	@Autowired
	private LocaleResolver localeResolver;

	@Autowired
	private MessageSource messageSource;

	@RequestMapping(value = "/changeLocale")
	public String changeLocale(HttpServletRequest request, HttpServletResponse response, String localeType) {
		if ("en_US".equals(localeType)) {
			localeResolver.setLocale(request, response, Locale.US);
		} else if ("zh_CN".equals(localeType)) {
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/students";
	}

	@RequestMapping("/students")
	public String students(Model model) {
		PagerModel<StudentVO> list = studentService.findAllByPage();
		model.addAttribute("user_id",
				messageSource.getMessage("student.id.message", null, LocaleContextHolder.getLocale()));
		model.addAttribute("user_name",
				messageSource.getMessage("student.name.message", null, LocaleContextHolder.getLocale()));
		model.addAttribute("gender",
				messageSource.getMessage("student.sex.message", null, LocaleContextHolder.getLocale()));
		model.addAttribute("birthday",
				messageSource.getMessage("student.birthday.message", null, LocaleContextHolder.getLocale()));
		model.addAttribute("tel",
				messageSource.getMessage("student.tel.message", null, LocaleContextHolder.getLocale()));
		model.addAttribute("address",
				messageSource.getMessage("student.add.message", null, LocaleContextHolder.getLocale()));
		model.addAttribute("edit", messageSource.getMessage("page.index.edit", null, LocaleContextHolder.getLocale()));
		model.addAttribute("delete",
				messageSource.getMessage("page.index.delete", null, LocaleContextHolder.getLocale()));
		model.addAttribute("operate",
				messageSource.getMessage("page.index.operate", null, LocaleContextHolder.getLocale()));
		model.addAttribute("studentList", list);
		return "student/studentList";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String toAdd(Model model) {
		model.addAttribute("studentvo", new StudentVO());
		return "student/add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(RedirectAttributes redirectAttributes, Model model, @Validated StudentVO studentvo,
			BindingResult result) {
		if (result.hasErrors()) {
			model.addAttribute("studentvo", studentvo);
			return "student/add";
		}
		try {
			studentService.createStudent(studentvo);
			redirectAttributes.addFlashAttribute("message", "添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "添加失败，可能用户ID已存在");
			return "redirect:/add";
		}
		return "redirect:/students";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String toEdit(Model model, @PathVariable Integer id) {
		Student student = studentService.getUserById(id);

		StudentVO vo = new StudentVO();
		BeanUtils.copyProperties(student, vo);
		if (student.getBirthday() != null) {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
			String str=sdf.format(student.getBirthday()); 
			vo.setBirthday(str);
		}

		model.addAttribute("studentvo", vo);
		return "student/edit";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(RedirectAttributes redirectAttributes, @Validated StudentVO studentvo, @PathVariable Integer id,
			BindingResult result) {
		// if (result.hasErrors()) {
		// return "student/edit";
		// }
		studentvo.setUser_id(id);
		try {
			studentService.editStudentVO(studentvo);
			redirectAttributes.addFlashAttribute("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/students";
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String delete(RedirectAttributes redirectAttributes, @PathVariable Integer id) {
		try {
			studentService.deleteStudent(id);
			redirectAttributes.addFlashAttribute("message", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/students";
	}

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public String upload(@RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpSession session,
			ModelMap model) {
		ExcelUtils excelUtils = new ExcelUtils();
		String fileName = file.getOriginalFilename();

		// 获取文件的后缀名
		String postfix = fileName.substring(fileName.lastIndexOf("."));

		if (excelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix)
				|| excelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
			try {
				studentService.saveStudentByExcel(file.getInputStream(), postfix);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("文件格式不正解");
		}
		return "redirect:/students";
	}

}
